package com.weeho.dongyong.utils;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.ByteArrayOutputStream;
import java.io.DataOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.URL;
import java.net.URLConnection;
import java.security.KeyManagementException;
import java.security.NoSuchAlgorithmException;
import java.util.Map;
import java.util.Set;


public class HttpUtils {
	
	
	final static Logger logger = LoggerFactory.getLogger(HttpUtils.class);

	/**
	 * post方式请求服务器(http协议)
	 * 
	 * @param url
	 *            请求地址
	 * @param content
	 *            参数
	 * @param charset
	 *            编码
	 * @return
	 * @throws java.security.NoSuchAlgorithmException
	 * @throws java.security.KeyManagementException
	 * @throws java.io.IOException
	 */
	public static byte[] post(String url, String content, String charset,String cookies,String contentType)
			throws IOException {
		URL console = new URL(url);
		URLConnection conn = console.openConnection();
		conn.setRequestProperty("Cookie", cookies);
		conn.setRequestProperty("accept", "*/*");  
        conn.setRequestProperty("connection", "Keep-Alive");  
        conn.setRequestProperty("user-agent",  
                "Mozilla/5.0 (Windows; U; Windows NT 5.1; en-US) AppleWebKit/525.13 (KHTML, like Gecko) Chrome/0.2.149.27 Safari/525.13");  
       // conn.setRequestProperty("Content-Type", "application/json"); //当请求是json格式时可使用次方式
		//conn.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");//奥点云中使用此方式
		conn.setRequestProperty("Content-Type", contentType);//奥点云中使用此方式
		//conn.connect();
		conn.setDoOutput(true);  
        conn.setDoInput(true);  
		DataOutputStream out = new DataOutputStream(conn.getOutputStream());
		out.write(content.getBytes(charset));
		// 刷新、关闭
		out.flush();
		out.close();
		InputStream is = conn.getInputStream();
		if (is != null) {
			ByteArrayOutputStream outStream = new ByteArrayOutputStream();
			byte[] buffer = new byte[1024];
			int len = 0;
			while ((len = is.read(buffer)) != -1) {
				outStream.write(buffer, 0, len);
			}
			is.close();
			return outStream.toByteArray();
		}
		return null;
	}


	public static byte[] postt(String url, String content, String charset,String cookies)
			throws IOException {
		URL console = new URL(url);
		URLConnection conn = console.openConnection();
		conn.setRequestProperty("Cookie", cookies);
		conn.setRequestProperty("accept", "*/*");
		conn.setRequestProperty("connection", "Keep-Alive");
		conn.setRequestProperty("user-agent",
				"Mozilla/5.0 (Windows; U; Windows NT 5.1; en-US) AppleWebKit/525.13 (KHTML, like Gecko) Chrome/0.2.149.27 Safari/525.13");
		 conn.setRequestProperty("Content-Type", "application/json"); //当请求是json格式时可使用次方式
		//conn.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");//奥点云中使用此方式
		//conn.setRequestProperty("Content-Type", contentType);//奥点云中使用此方式
		//conn.connect();
		conn.setDoOutput(true);
		conn.setDoInput(true);
		DataOutputStream out = new DataOutputStream(conn.getOutputStream());
		out.write(content.getBytes(charset));
		// 刷新、关闭
		out.flush();
		out.close();
		InputStream is = conn.getInputStream();
		if (is != null) {
			ByteArrayOutputStream outStream = new ByteArrayOutputStream();
			byte[] buffer = new byte[1024];
			int len = 0;
			while ((len = is.read(buffer)) != -1) {
				outStream.write(buffer, 0, len);
			}
			is.close();
			return outStream.toByteArray();
		}
		return null;
	}

	
	public static String post0String(String url, String content, String charset,String cookies,String contentType) throws IOException{
		byte [] bytes = HttpUtils.post(url, content, charset, cookies,contentType);
		logger.info("bytes is "+ bytes);
		if (null == bytes) {
			return null;
		}
		String result = new String(bytes,charset);
		logger.info(result);
		return result;
	}

	public static String post01String(String url, String content, String charset, String cookies) throws IOException {
		if(content == ""){
			return "";
		}
		byte[] bytes = HttpUtils.postt(url, content, charset, cookies);
		logger.info("bytes is " + bytes);
		if (null == bytes) {
			return null;
		}
		String result = new String(bytes, charset);
		logger.info(result);
		return result;
	}
	
	/**
	 * get方式请求服务器(http协议)
	 * 
	 * @param url
	 *            请求地址
	 * @param charset
	 *            编码
	 * @return
	 * @throws java.security.NoSuchAlgorithmException
	 * @throws java.security.KeyManagementException
	 * @throws java.io.IOException
	 */
	public static byte[] get(String url,String charset,String cookies)
			throws IOException {
		//SSLContext sc = SSLContext.getInstance("SSL");
		//sc.init(null, new TrustManager[] { new TrustAnyTrustManager() }, new java.security.SecureRandom());

		URL console = new URL(url);
		URLConnection conn =  console.openConnection();
		//conn.setSSLSocketFactory(sc.getSocketFactory());
		//conn.setHostnameVerifier(new TrustAnyHostnameVerifier());
		conn.setRequestProperty("Cookie", cookies);
		conn.connect();
		//DataOutputStream out = new DataOutputStream(conn.getOutputStream());
		//out.write(content.getBytes(charset));
		// 刷新、关闭
		//out.flush();
		//out.close();
		InputStream is = conn.getInputStream();
		if (is != null) {
			ByteArrayOutputStream outStream = new ByteArrayOutputStream();
			byte[] buffer = new byte[1024];
			int len = 0;
			while ((len = is.read(buffer)) != -1) {
				outStream.write(buffer, 0, len);
			}
			is.close();
			return outStream.toByteArray();
		}
		return null;
	}
	/**
	 * get方式请求服务器(http协议)
	 *
	 * @param url
	 *            请求地址
	 * @param charset
	 *            编码
	 * @return
	 * @throws java.security.NoSuchAlgorithmException
	 * @throws java.security.KeyManagementException
	 * @throws java.io.IOException
	 */
	public static byte[] get(String url,String charset)
			throws IOException {
		//SSLContext sc = SSLContext.getInstance("SSL");
		//sc.init(null, new TrustManager[] { new TrustAnyTrustManager() }, new java.security.SecureRandom());

		URL console = new URL(url);
		URLConnection conn =  console.openConnection();
		//conn.setSSLSocketFactory(sc.getSocketFactory());
		//conn.setHostnameVerifier(new TrustAnyHostnameVerifier());
//		conn.setRequestProperty("Cookie", cookies);
		conn.connect();
		//DataOutputStream out = new DataOutputStream(conn.getOutputStream());
		//out.write(content.getBytes(charset));
		// 刷新、关闭
		//out.flush();
		//out.close();
		InputStream is = conn.getInputStream();
		if (is != null) {
			ByteArrayOutputStream outStream = new ByteArrayOutputStream();
			byte[] buffer = new byte[1024];
			int len = 0;
			while ((len = is.read(buffer)) != -1) {
				outStream.write(buffer, 0, len);
			}
			is.close();
			return outStream.toByteArray();
		}
		return null;
	}
	
	/**
	 * get方式请求服务器(http协议)
	 * 
	 * @param url
	 *            请求地址
	 * @param charset
	 *            编码
	 * @return
	 * @throws java.security.NoSuchAlgorithmException
	 * @throws java.security.KeyManagementException
	 * @throws java.io.IOException
	 */
	public static String  getAsString(String url,String charset,String cookies)
			throws IOException {
		byte [] bytes = HttpUtils.get(url, charset,cookies);
		logger.info("bytes is "+bytes);
		if (null == bytes) {
			return null;
		}
		String result = new String(bytes,charset);
		logger.info(result);
		return result;
	}

	/**
	 * get方式请求服务器(http协议)
	 *
	 * @param url
	 *            请求地址
	 * @param charset
	 *            编码
	 * @return
	 * @throws java.security.NoSuchAlgorithmException
	 * @throws java.security.KeyManagementException
	 * @throws java.io.IOException
	 */
	public static String  getAsString(String url,String charset)
			throws IOException {
		byte [] bytes = HttpUtils.get(url, charset);
		logger.info("bytes is "+bytes);
		if (null == bytes) {
			return null;
		}
		String result = new String(bytes,charset);
		logger.info(result);
		return result;
	}
	public static byte[] get0(String url,  String charset,Map headers)
			throws NoSuchAlgorithmException, KeyManagementException, IOException {
//		SSLContext sc = SSLContext.getInstance("SSL");
//		sc.init(null, new TrustManager[] { new TrustAnyTrustManager() }, new java.security.SecureRandom());

		URL console = new URL(url);
		URLConnection conn =  console.openConnection();
//		conn.setSSLSocketFactory(sc.getSocketFactory());
//		conn.setHostnameVerifier(new TrustAnyHostnameVerifier());
		conn.setDoOutput(true);
		conn.setDoInput(true);
		if (headers != null && !headers.isEmpty()) {
			Set<String> keySet = headers.keySet();
			for (String key: keySet) {
				String value =  (String)headers.get(key);
				conn.setRequestProperty(key,value);
			}
		}
		conn.connect();
		InputStream is = conn.getInputStream();
		if (is != null) {
			ByteArrayOutputStream outStream = new ByteArrayOutputStream();
			byte[] buffer = new byte[1024];
			int len = 0;
			while ((len = is.read(buffer)) != -1) {
				outStream.write(buffer, 0, len);
			}
			is.close();
			return outStream.toByteArray();
		}
		return null;
	}

}
